import {Component, OnInit} from '@angular/core';
import {NzUploadFile} from 'ng-zorro-antd/upload';
import {NzMessageService} from 'ng-zorro-antd/message';
import {HttpClient} from '@angular/common/http';
import {CommodityCategoryService} from '../../commodity-category/commodity-category.service';
import {CommodityInfoService} from '../commodity-info.service';
import {ActivatedRoute, Router} from '@angular/router';

@Component({
  selector: 'app-commodity-add',
  templateUrl: './commodity-add.component.html',
  styleUrls: ['./commodity-add.component.scss']
})
export class CommodityAddComponent implements OnInit {
  formData = {
    id: '',
    name: null,
    code: null,
    state: 0,
    img: '',
    type: [] as any[],
    remark: null,
    brandId: null,
    stockUnit: null,
    shelfLife: null,
    weight: null,
    enclosure: [] as any,
    taxRate: null,
    costPrice: null,
    standardCostPrice: null,
    highestCostPrice: null,
    earlyWarning: null,
    snState: null,
    bomList: [] as any
  };
  goodsTypeList: any[] = [];
  unitList: any[] = [];
  brandList: any[] = [];
  bomModal = {
    visible: false,
    page: 1,
    pageSize: 10,
    listOfData: {} as any,
    whGood: '',
  };
  checked = false;
  indeterminate = false;
  isEdit = false;
  setOfCheckedId = new Set<number>();
  beforeUpload = (file: NzUploadFile): boolean => {
    const acceptFileType = [
      'bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif',
      'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps',
      'ai', 'raw', 'WMF', 'webp', 'avif', 'apng', 'pdf', 'txt',
      'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx',
    ];
    const fileName: any = file.name.split('.').pop();
    if (!acceptFileType.includes(fileName.toLowerCase())) {
      this.nzMessageService.warning('暂不支持该文件类型');
      return false;
    }
    const fileFormData = new FormData();
    // @ts-ignore
    fileFormData.append('file', file);
    fileFormData.append('name', (+new Date()).toString());
    this.httpClient.post('/common/upload/file', fileFormData).subscribe((res: any) => {
      if (res.code === 0) {
        console.log(res.data);
        this.formData.enclosure.push(res.data);
      }
    });
    return false;
  };

  constructor(
    private nzMessageService: NzMessageService,
    private httpClient: HttpClient,
    private commodityCategoryService: CommodityCategoryService,
    private commodityInfoService: CommodityInfoService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
  ) {
  }

  async ngOnInit() {
    const typeListRes = await this.getGoodsTypeList();

    const {code, data, message} = typeListRes;
    if (code !== 0) {
      this.nzMessageService.error(message);
      return;
    }
    this.goodsTypeList = this.getEditList(data);
    const id = this.activatedRoute.snapshot.queryParams.id;
    if (id) {
      this.isEdit = true;
      await this.commodityInfoService.getCommodityDetail(id).subscribe(res => {
        this.formData = {
          id,
          name: res.data.name,
          code: res.data.code,
          state: res.data.state,
          img: res.data.img,
          type: res.data.type,
          remark: res.data.remark,
          brandId: res.data.brandId,
          stockUnit: res.data.stockUnit,
          shelfLife: res.data.shelfLife,
          weight: res.data.weight,
          enclosure: res.data.enclosure ? JSON.parse(res.data.enclosure) : [],
          taxRate: res.data.taxRate,
          costPrice: res.data.costPrice,
          standardCostPrice: res.data.standardCostPrice,
          highestCostPrice: res.data.highestCostPrice,
          earlyWarning: res.data.earlyWarning,
          snState: res.data.snState,
          bomList: res.data.bomList ? JSON.parse(res.data.bomList) : []
        };
        let arr: any[] = [];
        let out = false;
        this.getTypeParent(this.goodsTypeList, arr, out);
      });
    }
    // 获取字典的 仓库商品单位
    this.httpClient.get('/dict/detail', {
      params: {
        parentKey: 'wh_goods_stock_unit',
        pageNum: '1',
        pageSize: '999'
      }
    }).subscribe((res: any) => {
      for (const key in res.data.list.records) {
        const element = res.data.list.records[key];
        this.unitList.push({
          label: element.name,
          value: element.content
        });
      }
      console.log(res);
    }, err => {
    });
    this.commodityInfoService.getBrandList({name: '', page: 1, pageSize: 999999}).subscribe((res: any) => {
      if (res.code !== 0) {
        this.nzMessageService.error(res.message);
        return;
      }
      this.brandList = res.data.records;
    });
  }

  getTypeParent(options: any, arr: any[], out: boolean) {
    let bg = 0;
    for (const item of options) {
      if (item.id === this.formData.type) {
        arr.push(item.id);
        out = true;
      } else if (item.children && item.children.length) {
        arr.push(item.id);
        this.getTypeParent(item.children, arr, out);
      }
      bg++;
      if (out) {
        this.formData.type = JSON.parse(JSON.stringify(arr));
        return;
      }
      if (bg === options.length && arr && arr.length > 0) {
        arr.pop();
      }
    }
  }

  /**
   * 商品分类下拉
   */
  getGoodsTypeList() {
    return this.commodityCategoryService.get().toPromise();
  }

  // 递归遍历所有的数组把id name 修改成 value title
  getEditList(list: any) {
    list?.forEach((item: any) => {
      const {id, name} = item;
      item.key = id;
      item.value = id;
      item.title = name;
      item.label = name;
      if (item.children?.length > 0) {
        this.getEditList(item.children);
      } else {
        item.isLeaf = true;
      }
    });
    return list;
  }

  selectCommodity() {
    console.log(this.formData);
  }

  removeCommodity(index: number) {
    this.formData.bomList.splice(index, 1);
    this.formData.bomList = JSON.parse(JSON.stringify(this.formData.bomList));
    console.log(this.formData);
  }

  bomQueryBtn() {
    this.bomModal.page = 1;
    this.getBomList();
  }

  bomResetCondition() {
    this.bomModal.page = 1;
    this.bomModal.pageSize = 10;
    this.bomModal.whGood = '';
    this.getBomList();
  }

  bomOnPageIndexChange(index: number) {
    this.bomModal.page = index;
    this.getBomList();
  }

  bomOnPageSizeChange(pageSize: number) {
    this.bomModal.pageSize = pageSize;
    this.getBomList();
  }

  showBomTable() {
    this.bomModal.visible = true;
    this.getBomList();
  }

  hideBomTable() {
    this.bomModal = {
      visible: false,
      page: 1,
      pageSize: 10,
      listOfData: {} as any,
      whGood: '',
    };
  }

  getBomList() {
    this.commodityInfoService.getBomList({
      page: this.bomModal.page,
      pageSize: this.bomModal.pageSize,
      whGood: this.bomModal.whGood
    }).subscribe(res => {
      console.log(res);
      this.bomModal.listOfData = res.data;
    });
  }

  onAllChecked(checked: boolean): void {
    this.bomModal.listOfData.records
      // @ts-ignore
      .filter(({disabled, status}) => !disabled && status !== 4)
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    // @ts-ignore
    const listOfEnabledData = this.bomModal.listOfData.records;
    // @ts-ignore
    this.checked = listOfEnabledData.every(({id}) => this.setOfCheckedId.has(id));
    // @ts-ignore
    this.indeterminate = listOfEnabledData.some(({id}) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  relevance() {
    const list = this.bomModal.listOfData.records.filter((item: any) => this.setOfCheckedId.has(item.id) && !this.formData.bomList.some((bom: any) => bom.id === item.id));
    console.log(this.setOfCheckedId);
    console.log(list);
    this.formData.bomList.push(...list);
    this.formData.bomList = JSON.parse(JSON.stringify(this.formData.bomList));
    this.hideBomTable();
  }

  save() {
    if (this.formData.name === null) {
      this.nzMessageService.error('请输入名称');
      return;
    }
    if (!this.formData.type.length) {
      this.nzMessageService.error('请选择分类');
      return;
    }
    if (this.formData.brandId === null) {
      this.nzMessageService.error('请选择品牌');
      return;
    }
    if (this.formData.stockUnit === null) {
      this.nzMessageService.error('请选择单位');
      return;
    }
    if (this.formData.taxRate === null) {
      this.nzMessageService.error('请输入税率');
      return;
    }
    if (this.formData.snState === null) {
      this.nzMessageService.error('请选择SN管控');
      return;
    }
    this.commodityInfoService.commodityAdd({
      ...this.formData,
      bomList: JSON.stringify(this.formData.bomList),
      type: this.formData.type[this.formData.type.length - 1],
      enclosure: JSON.stringify(this.formData.enclosure)
    }).subscribe(res => {
      if (res.code === 0) {
        this.nzMessageService.success('操作成功');
        this.router.navigate(['/storage-center/storageCommodityInfo']);
      }
    });
  }

  removeFile(index: any) {
    this.formData.enclosure.splice(index, 1);
  }
}
